package org.example.covid.appointedday;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.example.covid.entity.CountyEntity;
import org.example.covid.group.CountyGroupingComparator;

import java.io.IOException;

public class CountyTopNApp {

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        if (args.length < 4) {
            System.err.println("Usage: countytopn <in> <out> <date> <topn>");
            System.exit(2);
        }
        //1、获取job
        //创建Hadoop配置对象，使用默认配置
        Configuration conf = new Configuration();
        conf.set("mapreduce.framework.name", "local");
        //todo 指定日期，topN
        conf.set("date", args[2]);
        conf.set("topn", args[3]);
        //创建一个MR作业，取名叫做word count，名字可用于管理作业
        Job job = Job.getInstance(conf, CountyTopNApp.class.getSimpleName());

        //2、设置jar包路径
        //告诉job可以跟据App这个类的元数据信息找到MR的jar文件
        job.setJarByClass(CountyTopNApp.class);

        //3、关联mapper和reducer
        //将Mapper类加入job
        job.setMapperClass(MyMapper.class);
        //将Reducer类加入job
        job.setReducerClass(MyReducer.class);

        //4、设置最终输出的k,v类型
        //设置mapper阶段输出的key value 类型
        job.setMapOutputKeyClass(CountyEntity.class);
        job.setMapOutputValueClass(NullWritable.class);
        //设置MR最终输出的数据的Key类型,Value类型
        job.setOutputKeyClass(CountyEntity.class);
        job.setOutputValueClass(NullWritable.class);

        //设置Reducer数量
        //>=2会出现分区
        job.setNumReduceTasks(1);


        //todo 设置分组
        job.setGroupingComparatorClass(CountyGroupingComparator.class);
        //6、设置输入输出路径
        //设置输入数据从哪个目录正的文件中读
        FileInputFormat.addInputPath(job, new Path(args[0]));
        //设置输出数据存放的文件在哪个目录下
        Path output = new Path(args[1]);
        FileOutputFormat.setOutputPath(job, output);

        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(output)) {
            fs.delete(output, true);
        }
        //7、提交job
        //执行job并等待其结束，然后程序退出
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

    public static class MyMapper extends Mapper<LongWritable, Text, CountyEntity, NullWritable> {

        private CountyEntity outKey = new CountyEntity();
        private NullWritable outValue = NullWritable.get();

        /**
         * 每对k,v执行一次
         * input: <LongWritable, Text>
         * output: <CovidCountEntity,Text>
         *
         * @param key
         * @param value
         * @param context
         * @throws IOException
         * @throws InterruptedException
         */
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            //读取一行，进行切割
            String[] fileds = value.toString().split(",");
            String date = context.getConfiguration().get("date");
            if (date.equals(fileds[0])) {
                int n = fileds.length;
                outKey.set(fileds[2], fileds[1], Long.parseLong(fileds[n - 2]));
                //输出结果
                context.write(outKey, outValue);
            }
        }
    }


    public static class MyReducer extends Reducer<CountyEntity, NullWritable, CountyEntity, NullWritable> {
        /**
         * 相同州的被分为了一组
         * key和value相对应
         * 对value进行迭代相当于对key进行迭代
         * @param key
         * @param values
         * @param context
         * @throws IOException
         * @throws InterruptedException
         */
        @Override
        protected void reduce(CountyEntity key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
            int n = Integer.parseInt(context.getConfiguration().get("topn"));
            int i = 0;
            for (NullWritable value : values) {
                if (i < n) {
                    context.write(key, NullWritable.get());
                    i++;
                } else {
                    return;
                }
            }

        }
    }
}
